package com.zxy.basic.handler;

import com.zxy.basic.enums.Sex;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.log4j.Logger;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @program: mybatis
 * @description:
 * @author: zhangxiaoyang
 * @date: 2019-01-04 14:45
 **/
public class MyEnumTypeHandler extends BaseTypeHandler<Sex> {

    private Logger log = Logger.getLogger(MyEnumTypeHandler.class);


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Sex parameter, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) {
            log.info("使用MyEnumTypeHandler设置枚举参数");
            ps.setInt(i, parameter.getId());
        } else {
            ps.setObject(i, parameter.getId(), jdbcType.TYPE_CODE); // see r3589
        }
    }

    @Override
    public Sex getNullableResult(ResultSet rs, String columnName) throws SQLException {
        log.info("使用MyEnumTypeHandler设置结果集参数");
        String s = rs.getString(columnName);
        return s == null ? null : Sex.getSex(Integer.parseInt(s));
    }

    @Override
    public Sex getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);
        return s == null ? null : Sex.getSex(Integer.parseInt(s));
    }

    @Override
    public Sex getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String s = cs.getString(columnIndex);
        return s == null ? null : Sex.getSex(Integer.parseInt(s));
    }
}
